<?php
/**
 * Created by PhpStorm.
 * User: 张鹏
 * Date: 2017-03-01
 * Time: 上午 11:44
 * Versions：v1.00
 */

namespace app\common\model;


use think\Db;

class Card
{
    var $userId;
    var $auth;
    public function __construct()
    {
        $this->auth = model('Admin')->is('client')['state'];
        //获取当前user_id
        if (is_null($this->userId)) {
            $User=new \app\common\model\User;
            $userId = $this->userId = $User->getUserId();

        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }

    //会员卡绑定
    public function bind($user_id,$card_code,$password=''){
        //检查权限
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        if (!$user_id){
            return [
                'state' => 0,
                'errormsg' => 'user_id need'
            ];
        }
        if (!$card_code){
            return [
                'state' => 0,
                'errormsg' => 'need card_code'
            ];
        }
        $data['user_id'] = $user_id;
        if ($this->auth){
            $data['user_admin_id'] = $this->userId;
        }
        //检查卡号输入是否正确
        if(!is_numeric($card_code) or strlen($card_code) <8 or strlen($card_code)>20){
            return [
                'state'=>0,
                'errormsg' => ' card_code error'
            ];
        }
        //检查此卡是否已被绑定
        $card_info = Db::name('user_card')
            ->where('card_code',$card_code)
            ->where('state','1')
            ->find();
        if(!empty($card_info)){
            return [
                'state' => 0,
                'errormsg' => 'linked card'
            ];
        }
        $data['card_code'] = $card_code;
        $data['state'] = 1;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        if ($password){
            $data['password'] = md5($password);
        }
        $card_id = Db::name('user_card')->insertGetId($data);
        if(!$card_id){
            return [
                'state' => 0,
                'errormsg' => 'Binding error'
            ];
        }
        model('Action')->add('card_bind',$card_code,'bind');
        $card_info = $this->cardList($user_id);
        if($card_info['state']){
            $cards = $card_info['data'];
        }else{
            $cards = [];
        }
        return [
            'state' => 1,
            'data' => ['card_id'=>$card_id,'cards'=>$cards]
        ];
    }
    //会员卡注销
    public function unbind($card_id){
        if (!$card_id){
            return [
                'state' => 0,
                'errormsg' => 'need card_id'
            ];
        }
        //判断此实体卡号是否已被绑定
        $card_info = Db::name('user_card')
            ->where("user_card_id",$card_id)
            ->where("state",'1')
            ->find();
        if(!$card_info){
            return [
                'state' => 0,
                'errormsg' => 'card not find'
            ];
        }
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => "You Can't Cancel"
            ];
        }
        //实体卡注销
        $data['state'] = 2;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        //如果是管理员操作，添加管理员id
        if ($this->auth){
            $data['admin_user_id'] = $this->userId;
        }else{
            $data['user_id'] = $this->userId;
        }
        $res = Db::name('user_card')->where('user_card_id',$card_id)->update($data);
        model('Action')->add('card_unbind',$res,'unbind');
        $card_info = $this->cardList($card_info['user_id']);
        if($card_info['state']){
            $cards = $card_info['data'];
        }else{
            $cards = [];
        }
        if ($res){
            return [
                'state' => 1,
                'date'=>['cards'=>$cards]
            ];
        }else{
            return [
                'state' => 0,
                'errormsg' => 'cancel error'
            ];
        }
    }
    //获取会员卡列表
    public function cardList($user_id){
        if (!$user_id){
            return ['state'=>0,'errormsg'=> ' need user_id'];
        }
        $card_info = Db::name('user_card')->where("user_id=$user_id and state=1")->select();
        if(!$card_info){
            return ['state'=>0,'errormsg'=> 'not find'];
        }
        foreach ($card_info as $k=>$v){
            $card_info[$k]['card_code'] = substr_replace($v['card_code'], '****', 2, strlen($v['card_code']) - 6);
        }
        return ['state'=>1,'data'=>$card_info];
    }
    //根据card_code获得用户user_id
    public function getUserIdByCode($card_code) {
        if (!$card_code) {
            return [
                'state' => 0,
                'errormsg' => 'need card_code'
            ];
        }
        $where['card_code'] = "'$card_code'";
        $where['state'] = "1";
        $card_info = Db::name('user_card')
            ->where('card_code',$card_code)
            ->where('state','1')
            ->find();
        //判断card_code状态,查询结果
        if (empty($card_info)){
            return [
                'state' => 0,
                'errormsg' => 'card_code error'
            ];
        }
        return [
            'state' => 1,
            'data' => ['user_id' => $card_info['user_id']]
        ];
    }
    //获取当前用户的会员卡列表
    public function getCardList($filter,$user_id=''){

        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage'])&&$filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if ($user_id){
            $where = 'user_id='.$user_id.' and state=1';
        }else{
            $where = 'state=1';
        }
        //查询数据
        $card = Db::name('user_card')
            ->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order('create_time desc')
            ->select();
        //数据处理
        if (!empty($card)) {
            foreach ($card as $k => $v) {
                $user = model('User')->getInfoById($v['user_id']);
                $card[$k]['user_name'] = $user['set_name']?$user['set_name']:$user['user_name'];
                $card[$k]['headimgurl'] = $user['headimgurl'];
                $card[$k]['tel'] = $user['tel'];
                $card[$k]['create_time'] = timeString($v['create_time']);
                $user_admin = model('User')->getInfoById($v['user_admin_id']);
                $card[$k]['user_admin_name'] = $user_admin['set_name']?$user_admin['set_name']:$user_admin['user_name'];
                $card[$k]['admin_headimgurl'] = $user_admin['headimgurl'];
            }
        }
        //判断是否有下一页
        $pages = $pages + 1;
        $type_brand_b = Db::name('user_card')
            ->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order('create_time desc')
            ->select();
        if (!empty($type_brand_b)) {
            $more = 1;
        } else {
            $more = 0;
        }
        return [
            'state'=> 1,
            'data' => [
                'list' => $card,
                'more' => $more,
                'maxPerPage' => $maxPerPage
            ]
        ];
    }
    //获取会员卡的操作记录
    public function recordList($filter){
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        $user_ids = '';
        $where="";
        $order = 'create_time desc';
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage'])&&$filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if (isset($filter['keywords'])&&$filter['keywords']){
            if(preg_match("/^1[34578]\d{9}$/", $filter['keywords'])){
                $user_id = model('user')->exist(["tel"=>$filter['keywords']]);
                if (!$user_id['state']){
                    return $user_id;
                }
                $user_ids = $admin_ids = $user_id['data']['user_id'];
                $where = "user_id=$user_ids or user_admin_id=$admin_ids";
            }elseif(is_numeric($filter['keywords']) && strlen($filter['keywords'])==9){
                $where = "card_code = $filter[keywords]";
            }elseif($filter['keywords']!=''){
                $where = keywordSQL($filter['keywords'],'nickname,real_name,set_name');
                $user_info = db('user')->where($where)->field('user_id')->select();
                if (!$user_info){
                    return [
                        'state'=> 0,
                        'errormsg' => 'user not find'
                    ];
                }
                foreach ($user_info as $k => $v){
                    $user_ids .= $v['user_id'].',';
                }
                $user_ids = $admin_ids = substr($user_ids,0,-1);
                $where = "user_id in($user_ids) or user_admin_id in($admin_ids)";
            }
        }
        if (isset($filter['order'])&&$filter['order']){
            $order = 'create_time asc';
        }
        $card = Db::name('user_card')
            ->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order($order)
            ->select();
        if (!$card){
            return [
                'state'=>0,
                'errormsg'=> 'card_code not find'
            ];
        }
        if(!empty($card)){
            foreach ($card as $k => $v) {
                $card[$k]['card_code'] = substr_replace($v['card_code'],'****',2,strlen($v['card_code'])-6);
                if ($v['state'] == 2) {
                    $card[$k]['unbind'] = 1;
                }
                $user = model('User')->getInfoById($v['user_id']);
                $card[$k]['user_name'] = $user['set_name']?$user['set_name']:$user['user_name'];
                $card[$k]['tel'] = isset($user['tel'])?$user['tel']:'';
                $card[$k]['create_time'] = timeString($v['create_time']);
                $user_admin = model('User')->getInfoById($v['user_admin_id']);
                $card[$k]['user_admin_name'] = $user_admin['set_name']?$user_admin['set_name']:$user_admin['user_name'];
            }
        }
        //判断是否有下一页
        $pages = $pages + 1;
        $type_brand_b = Db::name('user_card')
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order('create_time desc')
            ->select();
        if (!empty($type_brand_b)) {
            $more = 1;
        } else {
            $more = 0;
        }
        return [
            'state' => 1,
            'data' =>[
                'list'=> $card,
                'more'=> $more,
                'maxPerPage' => $maxPerPage
            ]
        ];
    }
    //设置密码
    public function passwordSet($password,$card_code){
        if(!$this->userId){
            return [
                'state' => 0,
                'errormsg' => 'not find user'
            ];
        }
        if (!$card_code){
            return [
                'state' => 0,
                'errormsg' => 'need card_code'
            ];
        }
        if (!$password){
            return [
                'state' => 0,
                'errormsg' => 'need password'
            ];
        }
        //查询会员卡
        $card_info = Db::name('user_card')
            ->where('state','1')
            ->where('card_code',$card_code)
            ->where('user_id',$this->userId)
            ->find();
        if (empty($card_info)){
            return [
                'state' => 0,
                'errormsg' => 'card_code error'
            ];
        }
        if (isset($card_info['password']) && $card_info['password']){
            return [
                'state' => '1',
                'errormsg' => 'existing password'
            ];
        }
        $data['password'] = md5($password);
        $num = Db::name('user_card')
            ->where('card_code',$card_code)
            ->update($data);
        if (!$num){
            return [
                'state' => 0,
                'errormsg' => 'updata error'
            ];
        }
        return ['state'=>1];

    }
}